package com.budwk.app.sqfwV2.service.enterpriseWarrantyServe.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.EnterpriseWarrantyServeDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.enums.enterpriseWarrantyServe.EnterpriseWarrantyServeFileEnum;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sqfwV2.service.enterpriseWarrantyServe.EnterpriseWarrantyServeExcelService;
import com.budwk.app.sqfwV2.service.enterpriseWarrantyServe.EnterpriseWarrantyServePdfService;
import com.budwk.app.sqfwV2.service.enterpriseWarrantyServe.EnterpriseWarrantyServeService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SimpleCriteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.createExcelAndUpload;

/**
 * @author zhangp
 * @description TODO
 * @className PublicSecurityServiceImpl
 * @Date 11:58 2024/3/27
 */
@Slf4j
@IocBean
public class EnterpriseWarrantyServeServiceImpl implements EnterpriseWarrantyServeService {

    @Inject
    private EnterpriseWarrantyServePdfService enterpriseWarrantyServePdfService;

    @Inject
    private EnterpriseWarrantyServeExcelService enterprisreWarrantyServeExcelService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwFormSummaryService sqfwFormsummaryService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;


    @Override
    public void submitData(CompleteFlowTemplateCodeUpdateDTO dto) {

        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        // 组装参数
        CompleteFlowTemplateCodeUpdateDTO codeUpdateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        codeUpdateDTO.setCompleteFlow(dto.getCompleteFlow());
        codeUpdateDTO.setFormSummary(dto.getFormSummary());
        param.setCompleteFlowDataDTO(codeUpdateDTO);
        param.setUserId(SecurityUtil.getUserId());
        enterpriseWarrantyServePdfService.createPdfAndMsg(param);
    }

    @Override
    public Result<?> reGeneratePDF(String sqfwFlowId) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        param.setCompleteFlowId(sqfwFlowId);
        enterpriseWarrantyServePdfService.reCreatePdfAndMsg(param);
        return Result.success();
    }

    @Override
    public Result<?> downExcelLedger(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
        List<GenerateExcelUrlVO> generateExcelUrlVOS = enterprisreWarrantyServeExcelService.generateExcel(excelConfigList, SecurityUtil.getUserId(), reqVo.getSqfwIds());
        return Result.data(generateExcelUrlVOS);
    }

    @Override
    public List<String> isCheckDataBatch(List<String> sqfwIdList) {
        List<String> indexList = new ArrayList<>();
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList);
        cnd.and("type", "=", SqfwFormSummaryConstants.enterprise_warranty_serve);
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
        if (formSummaryList.isEmpty()) return indexList;
        for (EnterpriseWarrantyServeFileEnum item : EnterpriseWarrantyServeFileEnum.values()) {
            if (EnterpriseWarrantyServeFileEnum.ENTERPRISE_APPEAL_BOOK.getCode().equals(item.getCode())) {
                //企业诉求化解台账需要条件
                cnd.and("param_data ->>'enterpriseAppeal'", "=", String.valueOf(true));
                List<Sqfw_formSummary_new> enterpriseAppealList = sqfwFormsummaryNewService.query(cnd);
                if (enterpriseAppealList.isEmpty()) continue;
                indexList.add(item.getCode());
            } else {
                indexList.add(item.getCode());
            }
        }
        return indexList;
    }

    @Override
    public Result<?> downloadTemplate(String index, HttpServletResponse response) {
        EnterpriseWarrantyServeFileEnum enterpriseWarrantyServeFileEnum = EnterpriseWarrantyServeFileEnum.getEnterpriseWarrantyServeFileByCode(index);
        if (ObjectUtils.isEmpty(enterpriseWarrantyServeFileEnum)) {
            throw new ServiceException("模板不存在");
        }
        GenerateExcelUrlVO resultVO = new GenerateExcelUrlVO();
        String fileName = enterpriseWarrantyServeFileEnum.getName() + "." + enterpriseWarrantyServeFileEnum.getSuffix();
        String emptyTemplate = enterpriseWarrantyServeFileEnum.getEmptyTemplatePath();
        String filepath = CommonFormOfficeUtils.getTemplatePathByOS(emptyTemplate);
        if (enterpriseWarrantyServeFileEnum.getSuffix().contains("doc")) {
            ByteArrayOutputStream byteArrayOutputStream = CommonFormOfficeUtils.generateWordDocument(new HashMap<>(), emptyTemplate, null, System.currentTimeMillis());
            GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = CommonFormOfficeUtils.wordUpload(byteArrayOutputStream, enterpriseWarrantyServeFileEnum.getName(), null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(generateWordAndPdfUrlVO.getWordUrl());
        } else {
            ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
            excelFileCreateParam.setTemplatePath(filepath);
            excelFileCreateParam.setSheetParam(null);
            excelFileCreateParam.setDataList(Lists.newArrayList());
            excelFileCreateParam.setFileName(fileName);
            excelFileCreateParam.setListNotLastRow(null);
            resultVO.setCreateConditionFlag(true);
            resultVO.setExcelUrl(createExcelAndUpload(excelFileCreateParam));
        }
        return Result.data(resultVO);
        // 下载文件
        //CommonComponent.downFile(response, filepath, fileName);
    }

    @Override
    public Result<?> getShopInfoListByContent(String content, Integer pageSize, Integer pageNo, List<String> types) {
       /* if (ObjectUtils.isEmpty(types)) {
            List<String> typeList = new ArrayList<>();
            typeList.add(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
            types = typeList;
        }*/
        String type = SupportBusinessTypeEnum.ENTERPRISE_WARRANTY_SERVE.getCode();
        return Result.data(shopsBaseInfoService.getShopInfoByPlaceName(content, pageSize, pageNo, type));
    }

    @Override
    public Result<?> getFormSummaryInfoListByShopId(String shopBaseInfoId) {
        SimpleCriteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        criSql.andEquals(Sqfw_formSummary_new::getShopsBaseInfoId, shopBaseInfoId)
                .andEquals(Sqfw_formSummary_new::getType, SupportBusinessTypeEnum.ENTERPRISE_WARRANTY_SERVE.getName());
        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(cri);
        //当记录没有时组装数据
        if (ObjectUtil.isEmpty(formSummaryNew)) {
            EnterpriseWarrantyServeDTO enterpriseWarrantyServeDTO = new EnterpriseWarrantyServeDTO();
            Sqfw_formSummary_new formSummaryNewBuild = new Sqfw_formSummary_new();
            SqfwShopsBaseInfo info = shopsBaseInfoService.fetch(shopBaseInfoId);
            enterpriseWarrantyServeDTO.setPlaceName(info.getPlaceName());
            enterpriseWarrantyServeDTO.setAddress(info.getAddress());
            enterpriseWarrantyServeDTO.setBusinessRegisteredAddress(info.getAddress());
            enterpriseWarrantyServeDTO.setOperatorTelephone(info.getOperatorTelephone());
            enterpriseWarrantyServeDTO.setSocialCreditCode(info.getSocialCreditCode());
            enterpriseWarrantyServeDTO.setOperator(info.getOperator());
            formSummaryNewBuild.setParamData(JSON.toJSONString(enterpriseWarrantyServeDTO));
            formSummaryNewBuild.setShopsBaseInfoId(info.getId());
            formSummaryNewBuild.setShopsBaseInfo(info);
            return Result.data(formSummaryNewBuild);

        }
        return Result.data(formSummaryNew);
    }


    @Override
    public Result<?> downPdfLedger(DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.ENTERPRISE_WARRANTY_SERVE.getName());
        cnd.and(Sqfw_formSummary_new::getSqfwId, "in", reqVo.getSqfwIds());
        cnd.desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(cnd);
        List<String> sqfwFlowIdList = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
        Cnd cndFlow = Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdList);
        cndFlow.and(Sqfw_completeflow::getFileType, "like", "%" + SqfwFormSummaryConstants.enterprise_warranty_serve + "%")
                .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                .and(Sqfw_completeflow::getResourcePath, "!=", "error")
                .orderBy("create_date", "asc");
        List<Sqfw_completeflow> flwoList = sqfwCompleteflowService.query(cndFlow);
        if (!flwoList.isEmpty()) {
            List<String> pdfPathList = flwoList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
            String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, EnterpriseWarrantyServeFileEnum.ENTERPRISE_INFO_PDF.getName() + DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            generateExcelUrlVO.setExcelUrl(url);
        }
        generateExcelUrlVOS.add(generateExcelUrlVO);
        return Result.data(generateExcelUrlVOS);
    }
}
